package edu.esiag.isin.easyncloud.admin.repository;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import edu.esiag.isin.easyncloud.admin.models.Service;

@Repository
public class ServiceRepository {

	public static final String SERVICE_COLLECTION_NAME = "services";
	public static final String SERVICE_ID_CRITERIA = "id";
	public static final String SERVICE_STATE_CRITERIA = "state";

	@Autowired
	private MongoTemplate mongoTemplate;

	public MongoTemplate getMongoTemplate() {
		return mongoTemplate;
	}

	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	public void dropCollection() {
		if (mongoTemplate.collectionExists(SERVICE_COLLECTION_NAME)) {
			mongoTemplate.dropCollection(SERVICE_COLLECTION_NAME);
		}
	}

	public void createCollection() {
		if (!mongoTemplate.collectionExists(SERVICE_COLLECTION_NAME)) {
			mongoTemplate.createCollection(SERVICE_COLLECTION_NAME);
		}
	}

	public Service selectOne(String id) {
		Query query = new Query(Criteria.where(SERVICE_ID_CRITERIA).is(id));
		Service service = mongoTemplate.findOne(query, Service.class);
		return service;
	}

	public List<Service> selectAll() {
		List<Service> services = mongoTemplate.findAll(Service.class);
		return services;
	}

	public void insert(Service service) {
		 mongoTemplate.insert(service, SERVICE_COLLECTION_NAME);
	}

	public void updateState(String id,boolean state) {

		Query  query = new Query(Criteria.where(SERVICE_ID_CRITERIA).is(id));
		Service service = mongoTemplate.findOne(query, Service.class);
		
		Update update = new Update();
		update.set(SERVICE_STATE_CRITERIA, state);
		
		mongoTemplate.updateFirst(query, update, Service.class);
	}
}
